# !/usr/bin/env python3
# -*- coding: utf-8 -*-

import jieba
from qa_engine.nlp.cilin import CilinSimilarity

cilin = CilinSimilarity()


def get_score(word, arr):
    """
    词语语义相似度
    :param word:
    :param arr:
    :return:
    """
    score = cilin.sim2016(word, arr)
    return score


def get_similarity(word, entity):
    """
    词汇相似度计算
    :param word: 代匹配的词
    :param entity: 匹配的词列表
    :return:
    """
    for sub_attr in entity:
        if word in sub_attr or sub_attr in word:
            return sub_attr
        e = 0
        for w in range(len(word)):
            if word[w] == sub_attr[e]:
                e = e + 1
                if e == len(sub_attr):
                    return sub_attr
        w = 0
        for e in range(len(sub_attr)):
            if sub_attr[e] == word[w]:
                w = w + 1
                if w == len(word):
                    return sub_attr

    for sub_attr in entity:
        attr_arr = jieba.cut(sub_attr)
        max_score = 0
        max_attr = ''
        for a in attr_arr:
            score = get_score(word, a)
            if score > max_score:
                max_score = score
                max_attr = sub_attr
        if max_score > 0.8:
            return max_attr


# TODO: 未找到该函数的用处
def _build_sub_dicts(words, arcs):
    """
    为句子中的每个词语维护一个保存句法依存儿子节点的字典
    :param words: 分词列表
    :param arcs: 句法依存列表
    :return:
    """
    sub_dicts = []
    for idx in range(len(words)):
        sub_dict = dict()
        for arc_idx in range(len(arcs)):
            # 如果这个依存关系的头节点是该单词
            if arcs[arc_idx].head == idx + 1:
                if arcs[arc_idx].relation in sub_dict:
                    sub_dict[arcs[arc_idx].relation].append(arc_idx)
                else:
                    sub_dict[arcs[arc_idx].relation] = []
                    sub_dict[arcs[arc_idx].relation].append(arc_idx)
        sub_dicts.append(sub_dict)

    return sub_dicts


# TODO: 未找到该函数的用处
def _fill_ent(words, postags, sub_dicts, word_idx):
    """
    完善识别的部分实体
    :param words:
    :param postags:
    :param sub_dicts:
    :param word_idx:
    :return:
    """
    sub_dict = sub_dicts[word_idx]
    prefix = ''
    if 'ATT' in sub_dict:
        for i in range(len(sub_dict['ATT'])):
            prefix += _fill_ent(words, postags, sub_dicts,
                                sub_dict['ATT'][i])

    postfix = ''
    if postags[word_idx] == 'v':
        if 'VOB' in sub_dict:
            postfix += _fill_ent(words, postags, sub_dicts,
                                 sub_dict['VOB'][0])
        if 'SBV' in sub_dict:
            prefix = _fill_ent(words, postags, sub_dicts,
                               sub_dict['SBV'][0]) + prefix

    return prefix + words[word_idx] + postfix
